<?php
session_start();
if (!isset($_SESSION['username'])) {
    header('Location: login.php');
    exit();
}
require_once 'track_online.php';
$currentUser = $_SESSION['username'];
$qlDir = __DIR__ . '/ql';
$infoFile = $qlDir . '/info.json';
$userDir = __DIR__ . "/user/$currentUser";
$userChatFile = $userDir . '/chats.json';

// 初始化群聊和用户文件
if (!file_exists($infoFile)) {
    file_put_contents($infoFile, json_encode([]));
}
if (!is_dir($userDir)) {
    mkdir($userDir, 0777, true);
}
if (!file_exists($userChatFile)) {
    file_put_contents($userChatFile, json_encode([]));
}

$groups = json_decode(file_get_contents($infoFile), true);
$userChats = json_decode(file_get_contents($userChatFile), true);
$searchResult = [];
$searchQuery = '';
$message = '';

// 搜索逻辑
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['search_query'])) {
    $searchQuery = trim($_POST['search_query']);
    if (!empty($searchQuery)) {
        foreach ($groups as $id => $group) {
            // 排除当前用户创建的群聊
            if ($group['name'] === $searchQuery && $group['creator'] !== $currentUser) {
                $searchResult[] = [
                    'id' => $id,
                    'name' => $group['name'],
                    'description' => $group['description'],
                    'tags' => $group['tags'] ?? [],
                ];
            }
        }
        if (empty($searchResult)) {
            $message = '未找到相关群聊';
        }
    }
}

// 加入群聊逻辑
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['join_group_id'])) {
    $groupId = trim($_POST['join_group_id']);
    if (isset($groups[$groupId])) {
        // 检查用户是否已经加入该群聊
        $alreadyJoined = false;
        foreach ($userChats as $chat) {
            if ($chat['id'] === $groupId && $chat['type'] === 'group') {
                $alreadyJoined = true;
                break;
            }
        }
        if (!$alreadyJoined) {
            // 添加群聊到用户的聊天列表
            $userChats[] = [
                'id' => $groupId,
                'name' => $groups[$groupId]['name'],
                'type' => 'group',
            ];
            file_put_contents($userChatFile, json_encode($userChats));

            // 更新群聊的 people.json 文件
            $peopleFile = $qlDir . "/$groupId/people.json";
            if (!is_dir($qlDir . "/$groupId")) {
                mkdir($qlDir . "/$groupId", 0777, true);
            }
            if (!file_exists($peopleFile)) {
                file_put_contents($peopleFile, json_encode([]));
            }
            $people = json_decode(file_get_contents($peopleFile), true);
            if (!in_array($currentUser, $people)) {
                $people[] = $currentUser;
                file_put_contents($peopleFile, json_encode($people));
            }

            $message = '成功加入群聊';
        } else {
            $message = '您已加入该群聊';
        }
    } else {
        $message = '群聊不存在';
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>搜索群聊 | JIILCHAT</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
        }
        
        body {
            background-color: #f5f7fa;
            color: #333;
        }
        
        /* 顶部导航栏 */
        .navbar {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            background: #ffffff;
            padding: 12px 20px;
            display: flex;
            align-items: center;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            z-index: 100;
            border-bottom: 1px solid #e0e4e9;
        }
        
        .back-btn {
            background: none;
            border: none;
            color: #000;
            font-size: 20px;
            margin-right: 15px;
            cursor: pointer;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }
        
        .back-btn:hover {
            background: #e4e6eb;
        }
        
        .navbar-title {
            font-size: 18px;
            font-weight: 600;
            flex-grow: 1;
            color: #333;
        }
        
        /* 主内容区 */
        .content {
            margin-top: 70px;
            padding: 20px;
        }
        
        /* 消息提示 */
        .message {
            background-color: #d4edda;
            color: #155724;
            padding: 12px 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            font-weight: 500;
            display: flex;
            align-items: center;
            box-shadow: 0 3px 10px rgba(0,0,0,0.05);
        }
        
        .message i {
            margin-right: 8px;
        }
        
        /* 搜索框样式 */
        .search-container {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            margin-bottom: 25px;
        }
        
        .search-form {
            display: flex;
            gap: 10px;
        }
        
        .search-input {
            flex-grow: 1;
            padding: 14px;
            border: 1px solid #e0e4e9;
            border-radius: 12px;
            font-size: 16px;
            transition: all 0.3s ease;
            background: #f8f9fa;
        }
        
        .search-input:focus {
            border-color: #3498db;
            outline: none;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
        }
        
        .search-btn {
            background: #3498db;
            color: white;
            border: none;
            border-radius: 12px;
            padding: 0 25px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }
        
        .search-btn:hover {
            background: #2980b9;
            transform: translateY(-1px);
            box-shadow: 0 3px 10px rgba(0,0,0,0.1);
        }
        
        /* 搜索结果显示区域 */
        .results-container {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        }
        
        .results-title {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 20px;
            padding-bottom: 12px;
            border-bottom: 1px solid #f0f2f5;
            color: #333;
            display: flex;
            justify-content: space-between;
        }
        
        .count-badge {
            background: #e6f7ff;
            color: #3498db;
            padding: 2px 10px;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 600;
        }
        
        /* 群聊卡片 */
        .group-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 15px;
        }
        
        .group-card {
            display: flex;
            flex-direction: column;
            padding: 20px;
            border-radius: 15px;
            border: 1px solid #edf2f7;
            transition: all 0.3s ease;
            background: white;
        }
        
        .group-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.08);
            border-color: #e2e8f0;
        }
        
        .group-info {
            margin-bottom: 15px;
        }
        
        .group-name {
            font-weight: 700;
            font-size: 18px;
            margin-bottom: 10px;
            color: #2d3748;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .group-name::before {
            content: "";
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: #3498db;
        }
        
        .group-description {
            font-size: 15px;
            color: #4a5568;
            line-height: 1.5;
            margin-bottom: 15px;
        }
        
        .tags-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 20px;
        }
        
        .tag {
            background: #e6f7ff;
            color: #3498db;
            border-radius: 20px;
            padding: 5px 12px;
            font-size: 13px;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        
        .group-actions {
            display: flex;
            gap: 12px;
            margin-top: 10px;
        }
        
        .view-group-btn, .join-btn {
            flex: 1;
            text-align: center;
            padding: 10px 15px;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            border: none;
        }
        
        .view-group-btn {
            background: #e8f4ff;
            color: #3498db;
            border: 1px solid #cce6ff;
        }
        
        .view-group-btn:hover {
            background: #d1e7ff;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(52, 152, 219, 0.1);
        }
        
        .join-btn {
            background: #3498db;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }
        
        .join-btn:hover {
            background: #2980b9;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
        }
        
        .join-btn.joined {
            background: #38a169;
        }
        
        .join-btn.joined:hover {
            background: #2c884c;
            box-shadow: 0 4px 12px rgba(56, 161, 105, 0.3);
        }
        
        /* 空状态 */
        .empty-state {
            text-align: center;
            padding: 40px 20px;
        }
        
        .empty-icon {
            font-size: 72px;
            color: #cbd5e0;
            margin-bottom: 20px;
        }
        
        .empty-title {
            font-size: 20px;
            font-weight: 600;
            color: #718096;
            margin-bottom: 10px;
        }
        
        .empty-subtitle {
            font-size: 16px;
            color: #a0aec0;
            max-width: 500px;
            margin: 0 auto;
            line-height: 1.6;
        }
        
        /* 搜索状态 */
        .search-state {
            display: flex;
            justify-content: center;
            padding: 30px;
        }
        
        .loader {
            width: 48px;
            height: 48px;
            border: 5px solid #3498db;
            border-bottom-color: transparent;
            border-radius: 50%;
            display: inline-block;
            box-sizing: border-box;
            animation: rotation 1s linear infinite;
        }
        
        @keyframes rotation {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        } 
        
        /* 响应式调整 */
        @media (max-width: 768px) {
            .group-list {
                grid-template-columns: 1fr;
            }
            
            .search-form {
                flex-direction: column;
            }
            
            .search-btn {
                padding: 14px;
            }
            
            .group-actions {
                flex-direction: column;
            }
        }
        
        .search-hint {
            color: #a0aec0;
            font-size: 14px;
            margin-top: 15px;
            text-align: center;
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <div class="navbar">
        <button class="back-btn" onclick="location.href='index.php'">
            <i class="fas fa-arrow-left"></i>
        </button>
        <div class="navbar-title">加入群聊</div>
    </div>
    
    <div class="content">
        <?php if ($message): ?>
            <div class="message">
                <i class="fas fa-info-circle"></i>
                <?= htmlspecialchars($message) ?>
            </div>
        <?php endif; ?>
        
        <!-- 搜索区域 -->
        <div class="search-container">
            <form method="POST" class="search-form">
                <input 
                    type="text" 
                    name="search_query" 
                    class="search-input" 
                    placeholder="输入群名称搜索..." 
                    value="<?= htmlspecialchars($searchQuery) ?>" 
                    required
                >
                <button type="submit" class="search-btn">
                    <i class="fas fa-search"></i> 搜索群聊
                </button>
            </form>
            
            <?php if (empty($searchQuery) && !$message): ?>
                <div class="search-hint">
                    搜索您感兴趣的话题或群组名称加入群聊
                </div>
            <?php endif; ?>
        </div>
        
        <!-- 群聊搜索结果 -->
        <div class="results-container">
            <?php if (!empty($searchQuery)): ?>
                <div class="results-title">
                    搜索结果
                    <span class="count-badge"><?= count($searchResult) ?> 个群聊</span>
                </div>
            <?php elseif (!$message): ?>
                <div class="results-title">
                    发现群聊
                    <span class="count-badge">探索并加入</span>
                </div>
            <?php endif; ?>
            
            <div class="group-list">
                <?php if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($searchResult)): ?>
                    <div class="empty-state">
                        <div class="empty-icon">
                            <i class="fas fa-comments"></i>
                        </div>
                        <h3 class="empty-title">未找到群聊</h3>
                        <p class="empty-subtitle">请尝试不同的搜索词或创建您自己的群聊</p>
                    </div>
                <?php elseif (!empty($searchResult)): ?>
                    <?php foreach ($searchResult as $group): 
                        // 检查用户是否已加入
                        $alreadyJoined = false;
                        foreach ($userChats as $chat) {
                            if ($chat['id'] === $group['id'] && $chat['type'] === 'group') {
                                $alreadyJoined = true;
                                break;
                            }
                        }
                    ?>
                        <div class="group-card">
                            <div class="group-info">
                                <div class="group-name">
                                    <?= htmlspecialchars($group['name']) ?>
                                </div>
                                <div class="group-description">
                                    <?= !empty($group['description']) ? htmlspecialchars($group['description']) : '这是一个活跃的交流群，欢迎加入讨论' ?>
                                </div>
                            </div>
                            
                            <?php if (!empty($group['tags'])): ?>
                                <div class="tags-container">
                                    <?php foreach ($group['tags'] as $tag): ?>
                                        <div class="tag">
                                            <i class="fas fa-tag"></i> <?= htmlspecialchars($tag) ?>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                            
                            <div class="group-actions">
                                <a href="qlinfo.php?group_name=<?= urlencode($group['name']) ?>" class="view-group-btn">
                                    <i class="fas fa-home"></i> 查看群主页
                                </a>
                                <form method="POST" class="join-form">
                                    <input type="hidden" name="join_group_id" value="<?= htmlspecialchars($group['id']) ?>">
                                    <button type="submit" class="join-btn <?= $alreadyJoined ? 'joined' : '' ?>" <?= $alreadyJoined ? 'disabled' : '' ?>>
                                        <i class="fas <?= $alreadyJoined ? 'fa-check' : 'fa-user-plus' ?>"></i>
                                        <?= $alreadyJoined ? '已加入' : '加入群聊' ?>
                                    </button>
                                </form>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="empty-state">
                        <div class="empty-icon">
                            <i class="fas fa-search"></i>
                        </div>
                        <h3 class="empty-title">搜索加入群聊</h3>
                        <p class="empty-subtitle">
                            在搜索框中输入群聊名称，寻找您感兴趣的交流群组加入聊天
                        </p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <script>
        // 添加表单提交动画
        document.querySelectorAll('form').forEach(form => {
            form.addEventListener('submit', function() {
                const submitBtn = this.querySelector('button[type="submit"]');
                if (submitBtn) {
                    submitBtn.disabled = true;
                    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';
                }
            });
        });
        
        // 搜索框获取焦点效果
        const searchInput = document.querySelector('.search-input');
        if (searchInput) {
            searchInput.addEventListener('focus', function() {
                this.parentElement.parentElement.style.boxShadow = '0 8px 20px rgba(52, 152, 219, 0.15)';
            });
            
            searchInput.addEventListener('blur', function() {
                this.parentElement.parentElement.style.boxShadow = '0 5px 15px rgba(0,0,0,0.05)';
            });
        }
        
        // 按钮微动画
        document.querySelectorAll('.view-group-btn, .join-btn').forEach(btn => {
            btn.addEventListener('mouseenter', function() {
                this.style.transform = 'translateY(-2px)';
            });
            
            btn.addEventListener('mouseleave', function() {
                this.style.transform = 'translateY(0)';
            });
        });
    </script>
</body>
</html>